<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 提示框 -->
      <el-alert
        title="注意：只允许第三级分类设置相关参数"
        type="warning"
        :closable="false"
      >
      </el-alert>

      <!-- 选择框 -->
      <el-row>
        <el-col>选中商品分类：</el-col>
        <!-- clearable 删除键 -->
        <el-cascader
          v-model="pCateId"
          :options="pCateList"
          :props="pCateProps"
          @change="selePCate"
        ></el-cascader>
      </el-row>
      <!-- 数据表 -->
      <el-tabs v-model="activeTab" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisabled" @click="addBtn"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="doDeltag(scope.row, i)"
                  v-for="(tag, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-el-focus
                  v-if="scope.row.inputShow"
                  v-model="scope.row.inputText"
                  size="small"
                  class="addInp"
                  @blur="scope.row.inputShow = false"
                  @keyup.native="addTag(scope.row, $event)"
                ></el-input>
                <el-tag @click="scope.row.inputShow = true" v-else>
                  +NewTag
                </el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <!-- prop="渲染绑定的表数据tableDate中的哪个数据" -->
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <!-- slot-scope="scope" -->
              <template slot-scope="scope">
                <el-button
                  @click="toEdit(scope.row)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  @click="toDel(scope.row.attr_id)"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isDisabled" @click="addBtn"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                >
                  {{ tag }}
                </el-tag>

                <el-input
                  v-el-focus
                  v-if="scope.row.inputShow"
                  v-model="scope.row.inputText"
                  size="small"
                  class="addInp"
                  @change="addTag(scope.row)"
                  @blur="scope.row.inputShow = false"
                ></el-input>
                <el-tag @click="scope.row.inputShow = true" v-else>
                  +NewTag
                </el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- slot-scope="scope" -->
              <template slot-scope="scope">
                <el-button
                  @click="toEdit(scope.row)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  @click="toDel(scope.row.attr_id)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="dialogVisible"
      @close="onEdClosed"
      width="50%"
    >
      <el-form
        :rules="addFormRules"
        ref="addFormRef"
        :model="addMoodel"
        label-width="100px"
      >
        <el-input
          v-model="addMoodel.attr_name"
          placeholder="请输入内容"
        ></el-input>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->

    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="isEditShow"
      @close="onEdClosed"
      width="50%"
    >
      <el-form
        :rules="addFormRules"
        ref="addFormRef"
        :model="addMoodel"
        label-width="100px"
      >
        <el-input
          v-model="addMoodel.attr_name"
          placeholder="请输入内容"
        ></el-input>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditShow = false">取 消</el-button>
        <el-button type="primary" @click="doEditParam">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除提示框 -->

    <el-dialog
      title="您确定删除吗"
      :visible.sync="isDelShow"
      @close="onEdClosed"
      width="30%"
    >
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDelShow = false">取 消</el-button>
        <el-button type="primary" @click="doDel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pCateId: [], //分类id
      pCateList: [], //分类数据
      // 选择框配置
      pCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover',
      },
      // 新增参数
      addMoodel: {
        attr_name: '', //参数名称
        att_id: -1,
      },
      dialogVisible: false, //添加文本显示与否

      isEditShow: false, //编辑文本显示与否

      isDelShow: false, //删除文本显示与否

      isDelId: -1, //删除的ID
      activeTab: 'many', //tab页签激活显示的页签项

      manyTableData: [], //用来保存动态参数数据

      onlyTableData: [], //用来保存静态属性数据
      //添加表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getCateList() // 获取分类
  },

  computed: {
    //获取最后一位
    CateId() {
      if (this.pCateId.length == 3) return this.pCateId[2]

      return null
    },

    isDisabled() {
      return this.pCateId.length < 3
    },

    cateId() {
      if (this.pCateId.length === 3) {
        return this.pCateId[this.pCateId.length - 1]
      }
      return null
    },
    titleText() {
      if (this.activeTab == 'many') return '参数'
      else return '属性'
    },
  },
  methods: {
    // 下拉选择事件
    selePCate() {
      // console.log(this.pCateId);
      // 判断是否选中第三级
      if (this.pCateId.length < 3) {
        this.pCateId = []

        return this.$msgBox.alert('必须选择【第三级】哦', '系统警告')
      }
      this.getCatePams()
    },
    // 请求 分类参数
    async getCatePams() {
      const { data: res } = await this.$axios({
        method: 'get',
        url: `categories/${this.CateId}/attributes`,
        params: {
          sel: this.activeTab,
        },
      })
      // //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      // // //如果返回状态正常，将请求的数据保存在data中

      res.data.forEach((e) => {
        if (e.attr_vals.trim().length == 0) {
          e.attr_vals = []
        } else {
          e.attr_vals = e.attr_vals.split(' ')
        }
        e.inputShow = false
        e.inputText = ''
      })
      console.log(res)

      if (this.activeTab === 'many') this.manyTableData = res.data
      else this.onlyTableData = res.data
    },

    // 获取分类函数
    async getCateList() {
      const { data: res } = await this.$axios({
        method: 'get',
        url: 'categories',
      })
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      // //如果返回状态正常，将请求的数据保存在data中
      // console.log(res.data)
      this.pCateList = res.data
    },
    // tab点击事件
    tabClick() {
      console.log(this.activeTab)
      this.getCatePams()
    },
    // 点击添加对话框
    addBtn() {
      this.dialogVisible = true
    },
    // 确认添加
    async addParams() {
      //校验通过，发送请求完成添加参数或者属性
      const { data: res } = await this.$axios.post(
        `categories/${this.cateId}/attributes`,
        {
          attr_name: this.addMoodel.attr_name,
          attr_sel: this.activeTab,
        }
      )

      console.log(res)
      if (res.meta.status !== 201) {
        return this.$msg.error('添加' + this.titleText + '数据失败')
      }
      this.$msg.success('添加' + this.titleText + '数据成功')
      this.dialogVisible = false

      this.getCatePams()
    },
    // 清空表单
    onEdClosed() {
      this.addMoodel.attr_name = ''
    },

    // 点击编辑文本框
    toEdit(obj) {
      // 显示修改文本框
      this.isEditShow = true
      // 将值赋予输入框
      this.addMoodel.attr_name = obj.attr_name
      // console.log(this.addMoodel.attr_name)
      // 将修改id存进addMoodel中
      this.addMoodel.id = obj.attr_id
      // console.log(this.addMoodel.id)
    },
    // 确认修改
    async doEditParam() {
      const { data: res } = await this.$axios({
        url: `categories/${this.CateId}/attributes/${this.addMoodel.id}`,

        method: 'put',
        data: {
          attr_name: this.addMoodel.attr_name,
          attr_sel: this.activeTab,
        },
      })

      console.log(res)
      if (res.meta.status !== 200) {
        return this.$msg.error('修改' + this.titleText + '数据失败')
      }
      this.$msg.success('修改' + this.titleText + '数据成功')
      this.isEditShow = false

      this.getCatePams()
    },
    // 点击删除
    toDel(id) {
      // 显示提示文本
      this.isDelShow = true
      this.isDelId = id
    },
    // 确认删除
    async doDel() {
      const { data: res } = await this.$axios({
        url: `categories/${this.CateId}/attributes/${this.isDelId}`,

        method: 'delete',
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$msg.error('删除' + this.titleText + '数据失败')
      }
      this.$msg.success('删除' + this.titleText + '数据成功')
      this.isDelShow = false

      this.getCatePams()
    },
    // 添加tag
    async addTag(row, e) {
      if (e.code !== 'Enter') return
      // console.log(row)
      row.attr_vals.push(row.inputText)
      const { data: res } = await this.$axios({
        url: `categories/${row.cat_id}/attributes/${row.attr_id}`,

        method: 'put',
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        },
      })

      console.log(res)
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }

      row.inputText = ''
      row.inputShow = false
    },
    // 删除tag
    async doDeltag(row, i) {
      row.attr_vals.splice(i, 1)
      console.log(row.attr_vals)

      const { data: res } = await this.$axios({
        url: `categories/${row.cat_id}/attributes/${row.attr_id}`,

        method: 'put',
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        },
      })

      console.log(res)
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.$msg.success(res.meta.msg)
    },
  },
}
</script>

<style scope>
.el-row {
  margin: 15px 0px;
}
.el-tag {
  margin: 5px;
}
.addInp {
  width: 100px;
}
</style>